<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;

class AuthController extends Controller
{

    private static $userModel = null;

    private $auth = null;

    protected $currentDateTime;

    public function __construct()
    {
        parent::__construct();
        $this->getInstance();
        $this->currentDateTime = time();
    }

    public function getInstance(){
        if( !self::$userModel ){
            self::$userModel  = new Admin;
        }
    }
    /**
     * @OA\Post(
     *     path="/admin/login",
     *     tags={"管理员登录"},
     *     summary="登录",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"username", "password"},
     *                 @OA\Property(property="username", type="string", description="手机号",default="213"),
     *                 @OA\Property(property="password", type="string", description="密码"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function login(Request $request)
    {
        $post_data = $request->all();
        return self::$userModel->login($post_data);
    }


    /**
     * @OA\Post(
     *     path="/admin/logout",
     *     tags={"管理员登录"},
     *     summary="管理退出（清除token）",
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function logout()
    {
        return self::$userModel->logout();
    }

    /**
     * @OA\Post(
     *     path="/admin/refresh",
     *     tags={"管理员登录"},
     *     summary="刷新token",
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function refreshToken()
    {
        $response = array('status_code' => '2000');

        $this->initialAuth();

        if ($token = $this->auth->refresh(true, true)) {
            $response['data'] = [
                'access_token' => $token,
                'expires_in' => $this->currentDateTime + 86400*300 # 24小时过期
            ];
        } else {
            $response = [
                'status_code' => '5000',
                'msg' => '系统错误，无法生成令牌'
            ];
        }

        return response()->json($response);
    }

    private function initialAuth()
    {
        $this->auth = app('auth')->guard('admin');
        return;
    }
}
